//
//  MeViewController.m
//  HTHappySale
//
//  Created by 创维海通 on 2017/9/18.
//  Copyright © 2017年 zxyywy. All rights reserved.
//

#import "MeViewController.h"
#import "MeUserInfoViewController.h"
#import "MainViewController.h"
#import "MePurseViewController.h"
#import "QQGroupViewController.h"
#import "SetViewController.h"
#import "FeedbackViewController.h"
#import "WXAuth2ViewController.h"

//Model
#import "MeHTModel.h"

//Cell
#import "MeCollectionViewCell.h"
#import "ModelHTCollectionView.h"
#import "MeCollectionHeaderView.h"

//Tools
#import "UIImageView+WebCache.h"

//每个格子的高度
#define GridHeight 122
//每行显示格子的列数
#define PerRowGridCount 3
//每个格子的宽度
#define GridWidth (SCREEN_WIDTH/PerRowGridCount-4)

#define MeHeadIdentifyCell @"MeHeadView"
#define kMovieFooterView @"kMovieFooterView"
@interface MeViewController ()<UICollectionViewDelegateFlowLayout,UICollectionViewDataSource,HTDragCellTableViewDataSource,HTDragCellTableViewDelegate,MeCollectionHeaderDelegate>
{
    
}
@property (strong, nonatomic) IBOutlet ModelHTCollectionView *MeCollectionView;

@property (nonatomic, strong) NSMutableArray <MeHTModel *> *DataArr;

@property (nonatomic, strong) MeCollectionHeaderView *headerView;
@end

@implementation MeViewController
#define MeIdentifyCell  @"MeCell"

- (NSMutableArray<MeHTModel *> *)DataArr{
    if (!_DataArr) {
        NSArray *titleArr =  @[@"我的钱包",@"QQ群",@"用户反馈"];//         , @"其它业务2", @"其它业务3",@"其它业务4",@"其它业务5", @"其它业务6"];
        NSArray *imageArr = @[@"wallet",@"QQ", @"user",@"rest1",@"rest2", @"rest3",@"rest4",@"rest5"];
        
        _DataArr = [NSMutableArray new];
        for (NSInteger i=0; i<titleArr.count; i++) {
            MeHTModel *model = [MeHTModel new];
            model.title = titleArr[i];
            model.image = imageArr[i];
            [_DataArr addObject:model];
        }
    }
    return _DataArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //XIB
    UINib *contentNib = [UINib nibWithNibName:NSStringFromClass([MeCollectionViewCell class])
                                       bundle:[NSBundle mainBundle]];
    [self.MeCollectionView registerNib:contentNib forCellWithReuseIdentifier:MeIdentifyCell];
    
    //设置header
    UINib *headernib = [UINib nibWithNibName:NSStringFromClass([MeCollectionHeaderView class]) bundle:[NSBundle mainBundle]];
    [self.MeCollectionView registerNib:headernib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:MeHeadIdentifyCell];
    
    [self initCollection];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addNavigationLeftView:@"" andType:1];
    [self addNavigationMiddleView:@"我的"];
    [self addNavigationRightView:@"设置"];
    
    if(!HTCFUDFEmptyValue(kNickNameKey))
    {
        nickname =  HTCFUDFGetValue(kNickNameKey);
    }
    
    MainViewController *mainCtrol = (MainViewController *)self.tabBarController;
    [mainCtrol showTabBar];
    
    if(_headerView != nil)
    {
        UIImageView *headView = [_headerView viewWithTag:600];
        NSString *filePath = HTCFAppCacheDirectory;
        NSString *filePath2 = [NSString stringWithFormat:@"%@%@",filePath,@"/MyImage/pic.png"];
        
        NSString *ImgStr;
        if (!HTCFCheckObjectNull(kPortraitKey)) {
            ImgStr = [NSString stringWithFormat:@"%@%@",Img_URL,HTCFUDFGetValue(kPortraitKey)];
        }
        
        if(HTCFFileIsExist(filePath2)){
            NSData *data = [NSData dataWithContentsOfFile:filePath2];
            NSLog(@"%@",data);
            UIImage *image = [UIImage imageWithData:data];
            [headView setImage:image];
        }else if (ImgStr != nil && ImgStr.length >0)
        {
            [headView sd_setImageWithURL:[NSURL URLWithString:ImgStr] placeholderImage:HTCFQuickImage(@"Headportrait")];
        }else{
            headView.image = HTCFQuickImage(@"Headportrait");
        }
        UILabel *label = [_headerView viewWithTag:601];
        label.text = nickname;
    }
    
    authorizationCode = HTCFUDFGetValue(kAuthorizationKey);
    NSLog(@"%@",authorizationCode);
    if(HTCFStringIsNull(authorizationCode)){
        WXAuth2ViewController *wxAuth2VC = [[WXAuth2ViewController alloc] init];
        [self presentViewController:wxAuth2VC animated:YES completion:nil];
    }
}

- (void)initCollection{
    _MeCollectionView.adelegate = self;
    _MeCollectionView.adataSource = self;
    _MeCollectionView.alwaysBounceVertical = YES;
}

#pragma mark -collectionDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger )collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.DataArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:MeIdentifyCell forIndexPath:indexPath] ;
    [cell configureCell:self.DataArr[indexPath.row]];
    return cell ;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(GridWidth, GridHeight);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(1, 1, 1, 1);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //点击事件
    MeHTModel *model = self.DataArr[indexPath.row];
    [self skipController:model];
}

- (void)tableView:(ModelHTCollectionView *)tableView newArrayDataForDataSource:(NSArray *)newArray{
    //改变数组
    self.DataArr = [NSMutableArray arrayWithArray:newArray];
}

/**选中的cell完成移动，手势已松开*/
- (void)cellDidEndMovingInTableView:(ModelHTCollectionView *)tableView{
    //保存数据
    [self SaveUserDefaultsDataFunction:self.DataArr];
}

- (NSArray *)originalArrayDataForTableView:(ModelHTCollectionView *)tableView{
    return self.DataArr;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if(section == 0)
    {
        CGSize size = {SCREEN_WIDTH, 110};
        return size;
    }
    CGSize size = {0, 0};
    return size;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && kind == UICollectionElementKindSectionHeader) {
        _headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:MeHeadIdentifyCell forIndexPath:indexPath];
        _headerView.headerDelegate = self;
        return _headerView;
    }else{
        return nil;
    }
}

- (void)SaveUserDefaultsDataFunction:(NSArray *)ChangeArr{
    NSMutableArray *muArr = [NSMutableArray new];
    for (NSInteger i=0; i<ChangeArr.count; i++) {
        MeHTModel *model = ChangeArr[i];
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model] ;
        [muArr addObject:data];
    }
    NSLog(@"%@",muArr);
}

#pragma mark -Action
- (void)skipController:(MeHTModel *)model
{
    if ([model.title isEqualToString:@"我的钱包"]) {
        MePurseViewController *mePurseVC = [[MePurseViewController alloc] init];
        [self.navigationController pushViewController:mePurseVC animated:YES];
    }else if ([model.title isEqualToString:@"QQ群"])
    {
        QQGroupViewController *qqVC = [[QQGroupViewController alloc] init];
        [self.navigationController pushViewController:qqVC animated:YES];
    }else if ([model.title isEqualToString:@"用户反馈"])
    {
        FeedbackViewController *feedbackVC = [[FeedbackViewController alloc] init];
        [self.navigationController pushViewController:feedbackVC animated:YES];
    }
}

-(void)rightTapAction {
    SetViewController *setVC = [[SetViewController alloc] init];
    [self.navigationController pushViewController:setVC animated:YES];
}

#pragma mark -MeCollectionHeaderDelegate
- (void)NextController
{
    MeUserInfoViewController *meUserInfoVC = [[MeUserInfoViewController alloc] init];
    [self.navigationController pushViewController:meUserInfoVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
